{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Control Flow" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "We now know how to set variables of various types:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 1\n", "b = 3.14\n", "c = 'hello'\n", "d = [a, b, c]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "but this doesn't get us very far. One essential part of programming is **control flow** which is the ability to control how the program will proceed based on, e.g., conditions or running parts of the program multiple times." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``if`` statements" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "The simplest form of control flow is the ``if`` statement, which executes a block of code only if a certain condition is true (and optionally executes code if it is *not* true. The basic syntax for an if-statement is the following:\n", "\n", " if condition:\n", " # do something\n", " elif condition:\n", " # do something else\n", " else:\n", " # do yet something else\n", "\n", "Notice that there is no statement to end the if statement, and the\n", "presence of a colon (``:``) after each control flow statement. Python relies\n", "on **indentation and colons** to determine whether it is in a specific block of\n", "code." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "For example, in the following code:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 2\n", "\n", "if a == 1:\n", " print(\"a is 1, changing to 2\")\n", " a = 2\n", "\n", "print(\"finished\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The first print statement, and the ``a = 2`` statement are only executed if ``a`` is 1. The statement ``print(\"finished\")`` is executed in all cases, once Python exits the if statement." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "**Indentation is very important in Python, and the convention is to use four spaces (not tabs) for each level of indent.** Most code editors allow you to set the number of spaces you want to use for one tab and often detect this given some source code." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Back to the if-statements, the conditions in the statements can be anything that returns a boolean value. For example, ``a == 1``, ``b != 4``, and ``c <= 5`` are valid conditions, because they return either ``True`` or ``False`` depending on whether the statements are true or not." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Standard comparisons can be used (``==`` for equal, ``!=`` for not equal, ``<=`` for less or equal, ``>=`` for greater or equal, ``<`` for less than, and ``>`` for greater than), as well as logical operators (``and``, ``or``, ``not``). Parentheses can be used to isolate different parts of conditions, to make clear in what order the comparisons should be executed, for example:\n", "\n", " if (a == 1 and b <= 3) or c > 3:\n", " # do something\n", "\n", "More generally, any function or expression that ultimately returns ``True`` or ``False`` can be used.\n", "\n", "In particular, you can use booleans themselves:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 8\n", "cond = a==1 or a>7\n", "if cond:\n", " print(\"hit\")\n", "else:\n", " print(\"miss\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``for`` loops" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Another common structure that is important for controling the flow of execution are loops. Loops can be used to execute a block of code multiple times. The most common type of loop is the ``for`` loop. In its most basic form, it is straightforward:\n", "\n", " for value in iterable:\n", " # do things\n", "\n", "The ``iterable`` can be any Python object that can be iterated over. This includes lists or strings." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "for x in [3, 1.2, 'a']:\n", " print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for char in 'hello':\n", " print(char)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "A common for-loop is one where one loops over a range of integers given certain steps. To do this, we can use the ``range`` function. If given a single value, it will allow you to iterate from 0 to the value minus 1:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(5):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(3, 12):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(2, 20, 2): # the third entry specifies the \"step size\"\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you try iterating over a dictionary, it will iterate over the **keys** (not the values), in no specific order:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = {'a':1, 'b':2, 'c':3}\n", "for key in d:\n", " print(key)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But you can easily get the value with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for key in d:\n", " print(key, d[key])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Building programs" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "These different control flow structures can be combined to form programs. For example, the following program will print out a different message depending on whether the current number in the loop is less, equal to, or greater than 10:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for value in [2, 55, 4, 5, 12, 8, 9, 22]:\n", " if value > 10:\n", " print(\"Value is greater than 10 (\" + str(value) + \")\")\n", " elif value == 10:\n", " print(\"Value is exactly 10\")\n", " else:\n", " print(\"Value is less than 10 (\" + str(value) + \")\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write a program that will print out all the prime numbers (numbers divisible only by one and themselves) below 1000.\n", "\n", "Hint: the modulo operator ``%`` can be used to find the rest of a division of two numbers (e.g. for $x=20$ and $y=3$, we have $20/3=6.66667$ such that ``20 % 3`` gives $20-6\\cdot3 = 2$).\n", "We could also define this function ourselves:\n", "\n", " x-int(x//y)*y" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "20 % 3" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 20\n", "y = 3\n", "x - int(x//y)*y" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# enter your solution here\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exiting or continuing a loop" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "There are two useful statements that can be called in a loop - ``break`` and ``continue``. When called, ``break`` will exit the loop it is currently in:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(10):\n", " print(i)\n", " if i == 3:\n", " break" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "The other is ``continue``, which will ignore the rest of the loop and go straight to the next iteration:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(10):\n", " if i == 2 or i == 8:\n", " continue\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When checking if a value is prime, as soon as you have found that the value is divisible by a single value, the value is therefore not prime and there is no need to continue checking whether it is divisible by other values. Copy your solution from above and modify it to break out of the loop once this is the case." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# enter your solution here\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``while`` loops" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Similarly to other programming languages, Python also provides a ``while`` loop which is similar to a ``for`` loop, but where the number of iterations is defined by a condition rather than an iterator:\n", "\n", " while condition:\n", " # do something" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 1\n", "while a < 10:\n", " print(a)\n", " a = a * 1.5\n", "print(\"Once the while loop has completed, a has the value\", a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "the loop is executed until ``a`` is equal to or exceeds 10.\n", "\n", "**Note:** An often made mistake with ``for``/``while``-loops is that you forget to increment the running variable. Those of you who have never programmed an endless loop shall raise their hands now..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write a program (using a ``while`` loop) that will find the Fibonacci sequence up to (and excluding) 100000. The two first numbers are 0 and 1, and every subsequent number is the sum of the two previous ones, so the sequence starts ``[0, 1, 1, 2, 3, 5, ...]``.\n", "\n", "Optional: Store the sequence inside a Python list, and only print out the whole list to the screen once all the numbers are available. Then, check whether any of the numbers in the sequence are a square (e.g. ``0*0``, ``1*1``, ``2*2``, ``3*3``, ``4*4``) and print out those that are." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# enter your solution here\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 1 }